package cn.net;

import cn.net.vo.GitBranchDTO;
import cn.net.vo.GitProjectDTO;
import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class GitProjectInfoMain {

    private static final String targetDir="F:\\tmp1";
    private static final String init="#!/bin/bash\nworkpath=$(cd \"$(dirname \"$0\")\";pwd)\n";
    private static final String PRIVATE_TOKEN = "XuaxfRsSeq-ypH7Gcrtc";
    private static final int pageSize = 100;
    private static final Charset charsetFrom = StandardCharsets.ISO_8859_1;
    private static final Charset charsetTo = StandardCharsets.UTF_8;
    public static void main(String[] args) throws IOException {
//        getRemoteBranchs("http://10.115.200.104/vue/app-sys-vue.git","dong.zhang8@gientech.com","zhangdong123456");
//        command();
        List<GitProjectDTO> projects = getProjects();
        System.out.println(JSON.toJSONString(projects));
        StringBuilder clonesb = new StringBuilder(init);
        StringBuilder pullsb = new StringBuilder(init);
        for (GitProjectDTO project : projects) {
            if(project.isEmpty_repo()) {
                continue;
            }
            clonesb.append("cd ").append("$workpath").append("\n")
//            .append("git clone  --mirror ").append(project.getHttp_url_to_repo()).append(" ").append(project.getPath_with_namespace()).append("\n")
            .append("git clone ").append(project.getHttp_url_to_repo()).append(" ").append(project.getPath_with_namespace()).append("\n")
            .append("cd ").append(project.getPath_with_namespace()).append("\n");
            pullsb.append("cd ").append("$workpath").append("\n")
            .append("cd ").append(project.getPath_with_namespace()).append("\n")
            .append("git pull ").append("\n");

            for (GitBranchDTO branch : project.getBranchs()) {
                clonesb.append("git checkout \""+branch.getName()).append("\"\n");
                pullsb.append("git checkout \""+branch.getName()).append("\"\n")
                .append("git pull ").append("\n");
            }
            for (GitBranchDTO branch : project.getTages()) {
                clonesb.append("git checkout "+branch.getName()).append("\n");
            }
        }
        File file = new File(targetDir+"\\gitclone.sh");
        File pull = new File(targetDir+"\\gitpull.sh");
        if(!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        file.createNewFile();
        pull.createNewFile();
        try(FileOutputStream out = new FileOutputStream(file)) {
            out.write(clonesb.toString().getBytes());
        }        file.createNewFile();
        try(FileOutputStream out = new FileOutputStream(pull)) {
            out.write(pullsb.toString().getBytes());
        }

        System.out.println(clonesb.toString());
    }
    public static List<GitProjectDTO> getProjects() throws IOException {
        List<GitProjectDTO> projects = get("http://10.115.200.104/api/v4/projects",GitProjectDTO.class);
        for(GitProjectDTO gitProjectDTO :projects) {
            if(gitProjectDTO.isEmpty_repo()) {
                System.out.println("空项目："+JSON.toJSONString(gitProjectDTO));
            }else {
                gitProjectDTO.setBranchs(get(gitProjectDTO.get_links().getRepo_branches(),GitBranchDTO.class));
                gitProjectDTO.setTages(get(gitProjectDTO.get_links().getRepo_branches().replace("/branches","/tags"),GitBranchDTO.class));
            }
        }
        return projects;
    }
    public static  <T> List<T> get(String url,Class<T> type) throws IOException {
        List<T> projects = new ArrayList<>();
        int pageNo = 1;
        int totalPage = 1;
        while (pageNo <= totalPage) {
            HttpClient httpClient = new HttpClient();
            HttpMethod getMethod = new GetMethod(url+"?per_page=" + pageSize + "&page=" + pageNo);
            getMethod.addRequestHeader("PRIVATE-TOKEN", PRIVATE_TOKEN);
            httpClient.executeMethod(getMethod);
            totalPage = Integer.parseInt(getMethod.getResponseHeader("X-Total-Pages").getValue());
            projects.addAll(JSON.parseArray(new String(getMethod.getResponseBodyAsString().getBytes(charsetFrom),charsetTo), type));
            pageNo++;
        }
        return projects;
    }
    public static String command() throws IOException {
        Process exec = Runtime.getRuntime().exec("cmd /c  git --version");
        OutputStream outputStream = exec.getOutputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.writeTo(outputStream);
        System.out.println(baos.toString());
        return null;
    }
    public static void getRemoteBranchs(String url, String username, String password){
        try {
            File dir = new File("f:/dmp3");
            Collection<Ref> refList;
            UsernamePasswordCredentialsProvider pro = new UsernamePasswordCredentialsProvider(username, password);
            Git.cloneRepository().setURI(url).setCredentialsProvider(pro).setCloneAllBranches(true).setDirectory(dir).call();
            refList = Git.lsRemoteRepository().setRemote(url).setCredentialsProvider(pro).call();
            List<String> branchnameList = new ArrayList<>(4);
            for (Ref ref : refList) {
                String refName = ref.getName();
                if (refName.startsWith("refs/heads/")) {                       //需要进行筛选
                    String branchName = refName.replace("refs/heads/", "");
                    branchnameList.add(branchName);
                }
            }
            List<Ref> tags = Git.open(dir).tagList().call();
            for (Ref ref : tags) {
                String refName = ref.getName();
                System.out.println(refName);
                if (refName.startsWith("refs/tags/")) {                       //需要进行筛选
                    String branchName = refName.replace("refs/tags/", "");
                    branchnameList.add(branchName);
                    Git.init().setGitDir(dir).call();
                }
            }

            System.out.println("共用分支" + branchnameList.size() + "个");
            branchnameList.forEach(System.out::println);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
